

from flask import (
    Blueprint,
    make_response,
    request,
    jsonify
)
from utils.captcha import Captcha
from io import BytesIO
from utils.alsdk import alsms
from utils import restful, jfcache
from tools import get_random_number
from .forms import SMSCaptchaFrom
import qiniu
from tasks import send_sms_captcha


bp = Blueprint('common', __name__, url_prefix='/c')


@bp.route('/')
def index():
    return 'common index'


@bp.route('/sms_captcha/', methods=['POST'])
def sms_captcha():
    form = SMSCaptchaFrom(request.form)
    if form.validate():
        telephone = form.telephone.data
        captcha = get_random_number(number=4)
        print('发送的短信验证码是: ', captcha)
        send_sms_captcha.delay(telephone, captcha)
        return restful.success()
        # if alsms.send_sms(telephone, captcha):
        #     jfcache.set(telephone, captcha)
        #     return restful.success()
        # else:
        #     # return restful.params_error()
        #     # jfcache.set(telephone, captcha)
        #     return restful.success()
    else:
        return restful.params_error(message='参数错误')


@bp.route('/captcha/')
def graph_captcha():
    text,image = Captcha.gene_graph_captcha()
    jfcache.set(text.lower(), text.lower())
    # BytesIO: 自截留
    out = BytesIO()
    image.save(out, 'png')
    out.seek(0)
    resp = make_response(out.read())
    resp.content_type = 'image/png'
    return resp


@bp.route('/uptoken/')
def uptoken():
    access_ky = 'Stg_FuhoTzZ7wPNmbagdd2bBJyxE95-U_Lb8XY3L'
    secret_key = 'jWnJne9qGvPkm6PsIe08YTfvy-s9qdTzKmrbBl25'
    q = qiniu.Auth(access_ky, secret_key)

    bucket = 'jifengbbs'
    token = q.upload_token(bucket)
    return jsonify({'uptoken': token})
